package cn.edu.zut.cs.controller;

import cn.edu.zut.cs.pojo.Equipment;
import cn.edu.zut.cs.pojo.User;
import cn.edu.zut.cs.pojo.Weighing;
import cn.edu.zut.cs.service.EquipmentService;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@RestController
public class DownController {
    @Resource
    private EquipmentService equipmentService;


    @RequestMapping(value = "/UserExcelDownloads",method = RequestMethod.GET)
    public String UserExcelDownloads(HttpServletResponse response, HttpSession session)throws IOException {
        User loginUser = (User) session.getAttribute("loginUser");
        if(loginUser.getUserlevel()==1){
            Date date=new Date();
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("信息表");
            List<Equipment> UserExcelDownloads = equipmentService.UserExcelDownloads(loginUser);
            String fileName = "equipment" + ".xls";
            int rowNum = 1;
            String [] headers = {"设备名","称重总重量","单位","设备所属仓库","设备管理员"};
            HSSFRow row = sheet.createRow(0);
            for (int i = 0;i<headers.length;i++){
                HSSFCell cell = row.createCell((short) i);
                HSSFRichTextString text = new HSSFRichTextString(headers[i]);
                cell.setCellValue(text);
            }
            for (Equipment equipment : UserExcelDownloads){
                HSSFRow row1 = sheet.createRow(rowNum);
                row1.createCell((short) 0).setCellValue(new HSSFRichTextString(equipment.getEquid()));
                row1.createCell((short) 1).setCellValue(equipment.getTotalweight());
                row1.createCell((short) 2).setCellValue(new HSSFRichTextString(equipment.getEquunit()));
                row1.createCell((short) 3).setCellValue(new HSSFRichTextString(equipment.getEqulocation()));
                row1.createCell((short) 4).setCellValue(new HSSFRichTextString(equipment.getEquadmin()));
                rowNum++;

            }
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            workbook.write(response.getOutputStream());
            return null;
        } else{
            return "404";
        }

    }

}
